/**
 * Created by Administrator on 2018/5/10.
 */
import  axios from 'axios'
import { getRedirectpath } from './util'
const AUTH_SUCCESS = 'AUTH_SUCCESS'
const ERROR_MSG = 'ERROR_MSG'
const USER_DATA = 'USER_DATA'
const LOGOUT = 'LOGOUT'

const initState={
  redirectTo:'',
  msg:'',
  user:'',
  pwd:'',
  type:''
}
export function user(state=initState,action){
  switch (action.type){
    case AUTH_SUCCESS:
      return {...state,msg:'',redirectTo:getRedirectpath(action.payload),...action.payload}
    case USER_DATA:
       return {...state,...action.payload}
    case ERROR_MSG:
      return {...state,isAuth:false,msg:action.msg}
    case LOGOUT:
      return {...initState,redirectTo:'/login'}
    default:return state
  }
}
function auth_success(data){
  return {type:AUTH_SUCCESS,payload:data}
}

function errorMsg(msg) {
  return {msg, type: ERROR_MSG}
}

export function loadData(userinfo){
   return {type:USER_DATA,payload:userinfo}
}
export function regiest({user,pwd,repwd,type}){
  if(!user || !pwd || !type){
    return errorMsg('用户名密码必须输入')
  }
  if(pwd!==repwd){
    return errorMsg('密码和确认密码不一致')
  }

  return dispatch=>{
    axios.post('/user/regiest',{user,pwd,type}).then(res=>{
      if(res.status===200&&res.data.code===0){
         dispatch(auth_success({user,pwd,type}))
      }else{
         dispatch(errorMsg(res.data.msg))
      }
})
}
}

export function login({user,pwd}){
  if(!user || !pwd){
    return errorMsg('用户名密码必须输入')
  }

  return dispatch=>{
    axios.post('/user/login',{user,pwd}).then(res=>{
      if(res.status===200&&res.data.code===0){
        dispatch(auth_success(res.data.data))
      }else{
        dispatch(errorMsg(res.data.msg))
      }
    })
  }
}

export function update(data){
  return dispatch=>{
    axios.post('/user/update',data).then(res=>{
      if(res.status===200&&res.data.code===0){
        dispatch(auth_success(res.data.data))
      }else{
        dispatch(errorMsg(res.data.msg))
      }
    })
  }
}

export function logout(){
   return {type:LOGOUT}
}